package com.zygh.lz.config;

import com.zygh.lz.securitys.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author ms151
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Autowired
    LoginSuccessHandler loginSuccessHandler;


    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Autowired
    UserDetailServiceImpl userDetailService;

    @Autowired
    JwtLogoutSuccessHandler jwtLogoutSuccessHandler;

    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager());
        return jwtAuthenticationFilter;
    }

    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    private static final String[] URL_WHITELIST = {

            "/RecordController/insertIgnore",
            "/RecordController/findIllegalDataEnd",
            "/RecordController/findAll",
            "/updateAppNote",
            "/findAppNote",
            "/staffLogin",
            "/logout",
            "/captcha",
            "/favicon.ico",
            "/swagger-resources/**",
            "/webjars/**",
            "/images/**",
            "/configuration/ui",
            "/v2/api-docs/**",
            "/actuator/**",
            "/instances/**",
            "/*.html",
            "/**/*.html",
            "/**/*.css",
            "/**/*.js",
            "/**/*.jpg",
            "/webSocket/*",
            "/TrailerStatistics/*",
            "/Dricer/*",
            "/appLogin", "/findSectionById", "/signqd", "/sifnqt", "/findPostStatus", "/addLocation", "/addGps",
            "/findSpecialById", "/insertXdeclare", "/selectAllPatrolrecordById", "/selectAllGPSById", "/addProblem",
            "/fileUpload", "/updatePatrolrecord", "/addPatrolrecord", "/slectAllmessage", "/selectProblemByid",
            "/updaMessage", "/finalReading", "/delMessage", "/modifu", "/selectAllPatrolrecordById", "/selectTaskList",
            "/selectProblemByid", "/selectProblemPecord", "/selectProblemByid", "/selectProblemCheck", "/signCount/",
            "/signDetialMonth", "/selectdefault", "/uploadPictures", "/selectAllByProblemtype", "/deLogin",
            "/updateEquipage", "/insertEquipage", "/getEquipageById", "/findAreaById", "/addTrailerInfo",
            "/findTrailerInfo", "/uploadTrailer", "/findAppPlateAll", "/updateTrailer", "/findTrailierById",
            "/findAppParkAll", "/updateTrailerByBoard", "/findTrailerByBoard", "/onDutyOnLine", "/findTrailierInfoById",
            "/AppDumpTrailer/*", "/Statistics", "/General", "/index/*", "/findNoSync", "/roadRescue/acceptSchInf", "/roadRescue/acceptVehMsg", "/roadRescue/acceptCarCount",
            "/getTaskGroupTree", "/findDutyMessag", "/getEquipageById", "/insertEquipage", "/unbindingEquipment", "/getEquipageByQrcode", "/updateEquipage", "/signBindingEquipage",
            "/findAppParkAllBySearch", "/updateAppPark", "/addAppPark", "/appParkDel", "/internetFindAppParkAll"
            , "/internetUpdateAppPark", "/pictureCheck", "/pictureParkCheck", "/findAppParkInfoByCode",
            "/trailerHomeStats", "/trailerInfoStats", "/parkStats",
            "/serviceStatus/**", "/updateAppParkByBoard"
    };


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors().and().csrf().disable()

                // 登录配置
                .formLogin()
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)

                .and()
                .logout()
                .logoutSuccessHandler(jwtLogoutSuccessHandler)

                // 禁用session
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                // 配置拦截规则
                .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                .anyRequest().authenticated()

                // 异常处理器
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)

                // 配置自定义的过滤器
                .and()
                .addFilter(jwtAuthenticationFilter())
                .addFilterBefore(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)

        ;

    }

    /**
     * 登录配置，使用自定义的用户名密码验证过滤器
     */
    @Bean
    CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
        filter.setAuthenticationSuccessHandler(loginSuccessHandler);
        filter.setAuthenticationFailureHandler(loginFailureHandler);
        //可自定义登录接口请求路径
        //filter.setFilterProcessesUrl("");

        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService);
    }
}
